package cn.edu.ctbu.demo2.webapi;


import cn.edu.ctbu.demo2.core.PageUntils;
import cn.edu.ctbu.demo2.domain.Course;
import cn.edu.ctbu.demo2.domain.Score;
import cn.edu.ctbu.demo2.service.CourseService;
import cn.edu.ctbu.demo2.service.ScoreService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.StringUtils;

@RestController
@Slf4j
@RequestMapping("/webapi/course")
public class CourseRestController {
    @Autowired
    private CourseService courseService;


    @PostMapping("/insert")
    public Course insert(Course course){
        Course course1=courseService.Insert(course);
        return course1;
    }

    @GetMapping("/getbypage")
    public PageUntils getByPage(@RequestParam(value = "page", defaultValue = "0") Integer page,
                                @RequestParam(value = "size", defaultValue = "10") Integer size,
                                @RequestParam(value = "stu_no",defaultValue = "")String stu_no){

        /**
         * 按id排序
         */
        Sort sort=Sort.by(Sort.Direction.DESC,"id");

        Page<Course> coursePage;
        if(StringUtils.isEmpty(stu_no)){
            Pageable pageable= PageRequest.of(page,size,sort);
            coursePage = courseService.findAll(pageable);
        }else{
            Course course=new Course();
            course.setStu_no(stu_no);
            Pageable pageable=PageRequest.of(0,10,sort);
            ExampleMatcher matcher=ExampleMatcher.matching()
                    .withMatcher("name",ExampleMatcher.GenericPropertyMatchers.contains());
            Example<Course> example = Example.of(course,matcher);
            coursePage = courseService.findAll(example,pageable);
        }
        PageUntils pageUntils=new PageUntils(coursePage.getContent(),coursePage.getTotalElements());
        return pageUntils;
    }

    @GetMapping("/get/{id}")
    public Course get(@PathVariable Integer id){
        Course course=courseService.getById(id);
//        score.setPassword("");
        return course;
    }

    @PutMapping("/update")
    public Course update(Course course){
        //读取旧数据
        Course oldscore=courseService.getById(course.getId());
//        if(StringUtils.isEmpty(score.getPassword())){
        //没有新密码，那么就是旧密码
//            score.setPassword(oldstudent.getPassword());
//        }
        course=courseService.update(course);
        return course;
    }

    @DeleteMapping("/delete/{id}")
    public void  delete(@PathVariable Integer id){
        courseService.delete(id);
//        return student1;
    }

}
